package com.example.openguass.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.openguass.entity.Category;
import com.example.openguass.mapper.CategoryMapper;
import com.example.openguass.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.openguass.service.DishService;
import com.example.openguass.vo.CategoryPageVO;
import com.example.openguass.vo.CategoryVO;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xa
 * @since 2022-11-17
 */
@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    private CategoryMapper categoryMapper;
    private DishService dishService;
    @Autowired
    private void setCategoryMapper(CategoryMapper categoryMapper){
        this.categoryMapper = categoryMapper;
    }
    @Autowired
    private void setDishService(DishService dishService){
        this.dishService = dishService;
    }

    @Override
    public Boolean insert(CategoryVO categoryVO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryVO,category);
        category.setCreateDate(LocalDateTime.now());
        return categoryMapper.insert(category) > 0;
    }

    @Override
    public Boolean exit(String name) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("name",name);
        return categoryMapper.selectCount(wrapper) > 0;
    }

    @Override
    public Boolean update(CategoryVO categoryVO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryVO,category);
        category.setUpdateDate(LocalDateTime.now());
        return categoryMapper.updateById(category) > 0;
    }

    @Override
    public Boolean removeAllById(String categoryId) {
        if (categoryMapper.deleteById(categoryId) > 0){
            return dishService.setNullByCategoryId(categoryId);
        }
        return false;
    }

    @Override
    public IPage<Category> findPage(CategoryPageVO pageVO) {
        Page<Category> page = new Page<Category>(pageVO.getPageNo(),pageVO.getPageSize());
        //创建查询条件
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_date");
        return categoryMapper.selectPage(page,wrapper);
    }
}
